<template>
  <!-- 添加或修改客户对话框 -->
  <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="850px" append-to-body>
    <el-row>
      <el-col :span="18">
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          label-width="auto"
          :disabled="disabled"
          :class="{ 'detail-disabled': disabled }"
        >
          <el-form-item label="客户单位名称" prop="customerName">
            <el-input v-model="form.customerName" placeholder="请输入客户单位名称" />
          </el-form-item>
          <el-form-item label="客户类型" prop="customerType">
            <el-select v-model="form.customerType" placeholder="请选择客户类型" clearable>
              <el-option
                v-for="dict in dict.type.customer_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="客户标签" prop="tagId">
            <el-select v-model="form.tagId" placeholder="请选择客户标签" clearable>
              <el-option
                v-for="dict in dict.type.customer_tag"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value * 1"
              />
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="客户头像" prop="customerAvatar">
            <image-upload
              @input="
                (val) => {
                  form.customerAvatar = val
                }
              "
              :limit="1"
              :value="form.customerAvatar"
            />
          </el-form-item> -->
          <el-form-item label="联系人" prop="companyName">
            <!-- <el-select
              v-model="form.companyName"
              v-loading="companyLoading"
              filterable
              remote
              reserve-keyword
              placeholder="输入关键字可选择更多联系人"
              :remote-method="getOrgList"
              style="width: 100%"
              clearable
              @clear="
                () => {
                  getOrgList('')
                }
              "
            >
              <el-option v-for="item in companyList" :key="item.orgName" :label="item.orgName" :value="item.orgName" />
            </el-select> -->
            <el-input v-model="form.companyName" placeholder="请输入联系人" />
          </el-form-item>
          <el-form-item label="联系方式" prop="contactInfo">
            <el-input v-model="form.contactInfo" placeholder="请输入联系方式" />
          </el-form-item>

          <el-form-item label="职位" prop="position">
            <el-input v-model="form.position" placeholder="请输入职位" />
          </el-form-item>
          <template v-if="disabled">
            <el-form-item label="客情支出次数" prop="companyName"> {{ form.receptionCount }} </el-form-item>
            <el-form-item label="客情支出金额" prop="position"> {{ form.receptionAmount }}元</el-form-item>
            <el-form-item>
              <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="合同信息" name="contractDetails"
                  ><el-table
                    :data="activeData"
                    style="width: 100%"
                    @row-click="rowClick"
                    v-loading="activeLoading"
                    row-class-name="tableColumn"
                    :header-cell-style="{ background: '#fff' }"
                  >
                    <el-table-column prop="contractName" align="center" label="合同名称"> </el-table-column>
                    <el-table-column prop="contractNumber" align="center" label="合同编号"> </el-table-column>
                    <el-table-column prop="categoryName" align="center" label="合同分类"> </el-table-column>
                    <el-table-column prop="contractAmount" align="center" label="合同金额">
                    </el-table-column> </el-table
                ></el-tab-pane>
                <el-tab-pane label="项目信息" name="projectDetails"
                  ><el-table
                    :data="activeData"
                    style="width: 100%"
                    @row-click="rowClick"
                    v-loading="activeLoading"
                    row-class-name="tableColumn"
                    :header-cell-style="{ background: '#fff' }"
                  >
                    <el-table-column prop="projectName" align="center" label="项目名称"> </el-table-column>
                    <el-table-column prop="projectNumber" align="center" label="项目编号"> </el-table-column>

                    <el-table-column prop="projectManager" align="center" label="项目类型">
                      <template slot-scope="scope">
                        <dict-tag :options="dict.type.project_type" :value="scope.row.projectType" />
                      </template>
                    </el-table-column>

                    <el-table-column align="center" prop="projectLevel" label="项目级别">
                      <template slot-scope="scope">
                        <dict-tag :options="dict.type.project_level" :value="scope.row.projectLevel" />
                      </template>
                    </el-table-column> </el-table
                ></el-tab-pane>
              </el-tabs>
            </el-form-item>
          </template>
        </el-form>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer" v-if="!disabled">
      <el-button @click="open = false">取 消</el-button>
      <el-button type="primary" @click="submitForm" v-loading="saveLoading">确 定</el-button>
    </div>
    <contract-details
      :show="modelName === 'contractDetails'"
      :disabled="true"
      @cancel="handleOpenModel"
      :id="modelData.contractId"
    />
    <project-details
      :show="modelName === 'projectDetails'"
      :disabled="true"
      @cancel="handleOpenModel"
      :id="modelData.id"
    ></project-details>
  </el-dialog>
</template>
<script>
import { getCustomer, addCustomer, updateCustomer } from '@/api/biz/customer'
import { listProject } from '@/api/biz/project'
import { listInformation } from '@/api/biz/contract'
import { listOrganization } from '@/api/biz/organization'
import { recycleBinReview } from '@/api/biz/bin'
export default {
  name: 'CustomerDetails',
  components: {
    ContractDetails: () => import('@/components/biz/ContractDetails.vue'),
    ProjectDetails: () => import('@/components/biz/ProjectDetails.vue'),
  },
  props: {
    id: {
      type: Number | String,
      default: '',
    },
    show: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    bin: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      open: false,
      title: '',
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        customerName: [{ required: true, message: '请输入客户单位名称', trigger: 'blur' }],
        // companyName: [{ required: true, message: '单位名称不能为空', trigger: 'blur' }],
        // position: [{ required: true, message: '职位不能为空', trigger: 'blur' }],
        tagId: [{ required: true, message: '标签不能为空', trigger: 'change' }],
        customerType: [{ required: true, message: '客户类型不能为空', trigger: 'change' }],
      },
      companyList: [],
      companyLoading: false,
      saveLoading: false,
      modelName: '',
      modelData: {},
      activeData: [],
      activeName: 'contractDetails',
      activeLoading: false,
    }
  },
  dicts: ['customer_tag', 'project_level', 'project_type', 'customer_type'],
  watch: {
    show: {
      handler(val) {
        if (val === this.open) return
        this.open = val
      },
    },
    open: {
      handler(val) {
        this.reset()
        if (val) {
          if (this.disabled) {
            this.title = '客户详情'
          } else {
            this.title = !this.id ? '新增客户' : '修改客户详情'
          }
          if (this.id) {
            this.form.id = this.id
            const callback = (response) => {
              this.companyList = [{ orgName: response.data.companyName }]
              this.form = response.data
            }
            if (!this.bin) {
              getCustomer(this.id).then(callback)
            } else {
              recycleBinReview(this.id).then(callback)
            }

            this.getTabTableData()
            return
          }
          // this.getOrgList('')
        } else {
          this.$emit('cancel', false)
        }
      },
    },
  },
  methods: {
    getTabTableData() {
      const data = {
        customerId: this.form.id,
        pageNum: 1,
        pageSize: 50,
      }
      const successFn = (response) => {
        this.activeLoading = false
        this.activeData = response.rows
      }
      const failFn = () => {
        this.activeLoading = false
      }
      this.activeLoading = true
      if (this.activeName === 'projectDetails') {
        listProject(data).then(successFn).catch(failFn)
        return
      }
      if (this.activeName === 'contractDetails') {
        listInformation(data).then(successFn).catch(failFn)
        return
      }
    },
    rowClick(row) {
      this.handleOpenModel(this.activeName, row)
    },
    handleClick(tab, event) {
      this.activeData = []
      this.$nextTick(() => {
        this.getTabTableData()
      })
    },
    handleOpenModel(name = '', data = {}) {
      this.modelName = name
      this.modelData = data
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectIds: null,
        customerName: null,
        customerAvatar: null,
        companyName: null,
        contactInfo: null,
        position: null,
        tagId: null,
        customerType: null,
        tagList: [],
      }
      this.resetForm('form')
    },
    getOrgList(query = '') {
      this.companyLoading = true
      listOrganization({
        orgName: query || undefined,
        pageNum: 1,
        pageSize: 10,
      })
        .then((response) => {
          this.companyList = response.rows
          this.companyLoading = false
        })
        .catch(() => {
          this.companyLoading = false
        })
    },
    /** 提交按钮 */
    submitForm() {
      this.saveLoading = true
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCustomer(this.form)
              .then((response) => {
                this.saveLoading = false
                this.$modal.msgSuccess('修改成功')

                this.open = false
                this.$emit('refresh')
              })
              .catch(() => {
                this.saveLoading = false
              })
          } else {
            addCustomer(this.form)
              .then((response) => {
                this.saveLoading = false
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.$emit('refresh')
              })
              .catch(() => {
                this.saveLoading = false
              })
          }
        } else {
          this.saveLoading = false
        }
      })
    },
  },
}
</script>
<style>
.tableColumn {
  cursor: pointer;
}
</style>
